package itsm.isperp.module.controller.slm;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataRequest;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppCalendarConfig;
import itsm.isperp.module.entity.db.DbEntityFieldControl;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.entity.serviceCatalog.SrcService;
import itsm.isperp.module.entity.slm.SlmServiceAgreement;
import itsm.isperp.module.service.app.AppCalendarConfigService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.bpm.BpmProcessSettingService;
import itsm.isperp.module.service.db.DbEntityService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.project.ProjProjectServiceService;
import itsm.isperp.module.service.serviceCatalog.SrcServiceService;
import itsm.isperp.module.service.slm.SlmServiceAgreementService;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("slm/serviceAgreement")
public class SlmServiceAgreementController extends
		BaseController<SlmServiceAgreement> {

	/**
	 * 
	 */
	@Autowired
	protected SlmServiceAgreementService slmServiceAgreementService;

	@Autowired
	protected ProjProjectService projProjectService;

	@Autowired
	protected DbEntityService dbEntityService;

	@Override
	public SlmServiceAgreementService getService() {
		return slmServiceAgreementService;
	}

	@Autowired
	protected AppDictService appDictService;

	@Autowired
	protected SrcServiceService srcServiceService;

	@Autowired
	protected BpmProcessSettingService bpmProcessSettingService;

	@Override
	public String getPageTitle() {
		return "服务协议";
	}

	@Override
	@RequestMapping(value = { "manage", "" })
	public ModelAndView manage(HttpServletRequest req) {
		ModelAndView mv = super.manage(req);

		mv.addObject("slmType", appDictService.findByType("SLM_TYPE"));

		// 应用对象
		DataRequest dataEntity = new JqGridRequest();
		dataEntity.addFilterRule("useForSlm", JqGridFilterRuleOp.eq, "1");
		dataEntity.isPageable(false);
		dataEntity.setSelectColumns("id", "name");
		mv.addObject("applyObject", dbEntityService.findAll(dataEntity)
				.getContent());

		// 项目
		DataRequest dataProject = new JqGridRequest();
		dataProject.isPageable(false);
		dataProject.setSelectColumns("id", "name");
		mv.addObject("projectId", projProjectService.findAll(dataProject)
				.getContent());

		return mv;
	}

	@RequestMapping("list")
	@ResponseBody
	@Override
	public PageResponse<SlmServiceAgreement> list(JqGridRequest request,
			HttpServletRequest req) {

		return this.getService().findAll(request).toPage();

	}

	@RequestMapping("listDetail")
	@ResponseBody
	@Override
	public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
			HttpServletRequest req) {
		String projectId = req.getParameter("projectId");
		if (StringUtils.isNotEmpty(projectId)) {
			request.addFilterRule("project_id", JqGridFilterRuleOp.eq,
					projectId);
		}
		return this.getService().findAllDetailByRequest(request).toPage();

	}

	/**
	 * 服务级别编辑界面
	 * 
	 * @return 服务级别编辑界面视图
	 */
	@RequestMapping("edit")
	@Override
	public ModelAndView edit(String id, HttpServletRequest req) {

		ModelAndView mv = new ModelAndView(this.getModulePath() + "/edit");
		SlmServiceAgreement model = null;

		if (StringUtils.isEmpty(id)) {
			model = new SlmServiceAgreement();
			model.setId(HibernateUUIDGenerator.generate());
			model.setSlmType("SLA");
			model.setUseProjectCalendar(true);
			mv.addObject("editStatus", "0");
		} else {
			model = this.getService().findOne(id);
			mv.addObject("editStatus", "1");

		}

		mv.addObject("model", model);

		if (!StringUtils.isEmpty(model.getUserType())) {
			model.setUserTypes(model.getUserType().split(","));
		}

		if (StringUtils.isNotEmpty(model.getServiceProduct())) {
			model.setServiceProducts(model.getServiceProduct().split(","));
		}

		mv.addObject("pageTitle", this.getPageTitle());

		// 基本信息控件初始化
		mv.addObject("slmTypes", appDictService.findByType("SLM_TYPE"));

		mv.addObject("slmStatus", appDictService.findByType("SLM_STATUS"));

		//
		mv.addObject("serviceWays", appDictService.findByType("SERVICE_WAY"));

		// 适应范围控件初始化
		mv.addObject("userTypes", appDictService.findByType("USER_TYPE"));

		DataRequest projectRequest = new JqGridRequest().isPageable(false)
				.setSelectColumns("id", "name");
		String projectId = req.getParameter("projectId");
		if (StringUtils.isNotEmpty(projectId)) {
			model.setProjectId(projectId);
			projectRequest
					.addFilterRule("id", JqGridFilterRuleOp.eq, projectId);
		}

		DataResponse<ProjProject> projects = projProjectService
				.findAll(projectRequest);
		mv.addObject("projects", projects);

		ProjProjectServiceService pss = ContextHolder
				.getSpringBean("projProjectServiceService");

		if (StringUtils.isEmpty(model.getProjectId())) {
			if (projects != null && !projects.isEmpty())
				projectId = projects.get(0).getId();
		}

		JqGridRequest srcReq = new JqGridRequest();
		srcReq.isPageable(false);
		srcReq.setSelectColumns("id", "CONCAT(code,'-',name) AS name");
		srcReq.addFilterRule("status", JqGridFilterRuleOp.eq, "发布");
		DataResponse<SrcService> srcList=null;
		if(StringUtils.isEmpty(projectId))
		{
		  srcList = pss.getAllSrcService(srcReq);
		}else
		{
		  srcReq.setSearchString(" pid='"+projectId+"'");
		  srcList = pss.getAllSrcService(srcReq);
		}
		
		AppCalendarConfigService appCalendarConfigService = ContextHolder.getSpringBean("appCalendarConfigService");
    List<AppCalendarConfig> list = appCalendarConfigService.findAll(new JqGridRequest().isPageable(false).setSelectColumns("id", "name"));
    mv.addObject("appCalendars", list);

		mv.addObject("serviceProducts", srcList);

		mv.addObject("applyObjects",
				bpmProcessSettingService.findProcessDbForSlmEntityList());
		return mv;
	}

	@Override
	@RequestMapping("save")
	@ResponseBody
	public ResultMessage save(SlmServiceAgreement model, HttpServletRequest req) {

		if (model.getUserTypes() != null && model.getUserTypes().length > 0) {
			String userTypes = model.getUserTypes()[0];
			int length = model.getUserTypes().length;
			for (int i = 1; i < length; i++) {
				userTypes += "," + model.getUserTypes()[i];
			}

			model.setUserType(userTypes);
		}

		if (model.getServiceProducts() != null
				&& model.getServiceProducts().length > 0) {
			String serviceProducts = model.getServiceProducts()[0];
			int length = model.getServiceProducts().length;
			for (int i = 1; i < length; i++) {
				serviceProducts += "," + model.getServiceProducts()[i];
			}
			model.setServiceProduct(serviceProducts);
		}
		this.getService().saveOrUpdate(model, req);
		return ResultMessage.newInstance(true, null, model.getId());
	}

	@RequestMapping("getSlm")
	@ResponseBody
	public List<Map<String, Object>> getSlm(String projectId,
			String processKey, String businessKey) {
		return this.getService().matchSlmList(projectId, processKey,
				businessKey);
	}

	@RequestMapping("getAgreementTargetDb")
	@ResponseBody
	public ResultMessage getTargetDb(String agreementId) {
		DbEntityFieldControl dbEntityFieldControl = slmServiceAgreementService
				.findSlmMonitorFieldControl(agreementId);

		return ResultMessage.success(appDictService.findLastOneByFilter(
				dbEntityFieldControl.getFilter()).getName());
	}

}
